package com.haonan.springboot_exercise.netty.server;

import com.alibaba.fastjson.JSON;
import com.haonan.springboot_exercise.bean.pojo.MsgResult;
import com.haonan.springboot_exercise.service.PopServerService;
import com.haonan.springboot_exercise.service.SmtpServerService;
import com.haonan.springboot_exercise.util.SpringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author haonan
 * @date 2021/4/17 18:52
 **/
@Slf4j
public class PopServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 客户端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("Channel active......");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 注意，非Controller层不能使用@Autowried注入，注入的对象为null；这里通过工具类注入
        PopServerService popServerService = SpringUtil.getBean(PopServerService.class);

        String msgStr = msg.toString();

        if(msgStr.equals("CLOSE_POP")){
            ctx.channel().parent().close();
        }

        log.info("服务器收到消息: {}", msgStr);
        // 命令
        String command = msgStr.substring(0,4);
        // 内容
        String payload = msgStr.substring(5);
        switch (command) {
            case "LIST": ctx.writeAndFlush(popServerService.getLISTResult(payload)); break;
            default : ctx.writeAndFlush(JSON.toJSONString(new MsgResult(400,"Failed"))); break;
        }
    }

    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}
